﻿//======================================================================
//  XML文件书写器,用来修改配置文件的信息,通常是客户修改配置
//====================================================================== 

namespace Common
{
    using System;
    using System.Data;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Text;
    using System.Xml;
    using System.Configuration;
    using System.Web.Configuration;
    using System.Web;
    using System.IO;

    /// <summary>
    /// XML文件书写器,用来修改配置文件的信息,通常是客户修改配置
    /// </summary>
    public class XmlWriter
    {
        /// <summary>
        /// 设置web.config中SiteConfigFile节点指定的配置文件内容
        /// </summary>
        /// <param name="Target">配置文件中的节点名称</param>
        /// <param name="configValue">该节点的需要赋的新值</param>
        /// <returns>设置是否成功</returns>
        public static bool SetConfigValue(string Target,string configValue)
        {
            string path = HttpContext.Current.Server.MapPath("~") + ConfigurationSettings.AppSettings["SiteConfigFile"];
            return SetConfigValue(Target,configValue, path);
        }

        /// <summary>
        /// 读取配置文件中指定节点的InnerText值
        /// </summary>
        /// <param name="Target">配置文件中的节点名称</param>
        /// <param name="ConfigValue">该节点的需要赋的新值</param>
        /// <param name="ConfigPathName">配置文件的路径</param>
        /// <returns>设置是否成功</returns>
        public static bool SetConfigValue(string Target,string ConfigValue, string XmlPath)
        {
            try
            {
                System.Xml.XmlDocument xdoc = new XmlDocument();
                xdoc.Load(XmlPath);
                XmlElement root = xdoc.DocumentElement;
                XmlNodeList elemList = root.GetElementsByTagName(Target);
                elemList[0].InnerText = ConfigValue;
                return true;
            }
            catch (Exception ex)
            {
                Logger.WriteLog("后台写配置文件出错:" + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 使用xpath获取指定节点的内容
        /// </summary>
        /// <param name="xpath">xpath表达式</param>
        /// <param name="XmlPath">配置文件路径</param>
        /// <param name="configValue">节点的新值</param>
        /// <returns>设置是否成功</returns>
        public static bool SetSingleNode(string xpath, string XmlPath,string configValue)
        {
            try
            {
                System.Xml.XmlDocument xdoc = new XmlDocument();
                xdoc.Load(XmlPath);
                XmlElement root = xdoc.DocumentElement;
                XmlNode node = root.SelectSingleNode(xpath);
                node.InnerText = configValue;
            }
            catch (Exception ex)
            {
                Logger.WriteLog("后台写配置文件出错:" + ex.Message);
                return false;
            }
            return true;
        }
    }
}
